package com.okaixz.client.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.okaixz.client.mapper.CsjJiliOrderMapper;
import com.okaixz.client.model.domain.CsjJiliOrder;
import com.okaixz.client.model.domain.Goods;
import com.okaixz.client.model.domain.User;
import com.okaixz.client.model.dto.CsjJiliParams;
import com.okaixz.client.model.dto.UserDto;
import com.okaixz.client.model.vo.GetJiliListResult;
import com.okaixz.client.service.ICsjJiliOrderService;
import com.okaixz.client.service.IGoodsService;
import com.okaixz.client.service.IUserService;
import com.okaixz.common.client.exception.BusinessException;
import com.okaixz.common.client.exception.CommonErrorCode;
import com.okaixz.common.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdz
 * @since 2025-08-11
 */
@Service
@Slf4j
public class CsjJiliOrderServiceImpl extends ServiceImpl<CsjJiliOrderMapper, CsjJiliOrder> implements ICsjJiliOrderService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;

    @Override
    public String processJiliCallback(CsjJiliParams params) {
        boolean isValid=true;
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("isValid",isValid);
        if (params == null) {
            return jsonObject.toString();
        }

        String sign = params.getSign();
        String user_id = params.getUser_id();
        String trans_id = params.getTrans_id();
        int reward_amount = params.getReward_amount();
        String reward_name = params.getReward_name();
        String extra = params.getExtra();

        log.info("收到csj激励回调："+params);


        return jsonObject.toString();
    }

    @Override
    @Transactional
    public UserDto jiliReward(CsjJiliParams params) {
        UserDto userDto=null;
        if (params == null) {
            throw new BusinessException(CommonErrorCode.PARAM_ERROR);
        }
        String user_id = params.getUser_id();
        Integer type = params.getType();
        if(user_id==null||type==null){
            throw new BusinessException(CommonErrorCode.PARAM_ERROR);
        }
        User user = userService.getUserFormRedisOrDb(user_id);
        if (user == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        CsjJiliOrder csjJiliOrder=new CsjJiliOrder();
        if(type==1){//aikb激励视频
            //判断今日是否已经达到上限 只有没达到上限才给奖励

            int limitNum = 0;
            GetJiliListResult result = jiliOrderList(user_id, 1);
            List<CsjJiliOrder> list = null;
            if (result != null) {
                list=result.getList();
                if (result.getLimitNum() != null) {
                    limitNum=result.getLimitNum();
                }
            }
            if(list==null||list.size()<limitNum){
                userDto=userService.updateVipInfo(14,user_id);
                csjJiliOrder.setStatus(CommonConstants.JILI_REWARD_STATUS_SUCCESS);
            }else {
                log.info("用户id="+user_id+"激励视频超出上限");
                csjJiliOrder.setStatus(CommonConstants.JILI_REWARD_STATUS_OUT_LIMT);
            }
            csjJiliOrder.setGid(14);
        }
        //测试事务
//        int a=0;
//        int b=10/a;
        csjJiliOrder.setUserId(user_id);
        csjJiliOrder.setTransId(params.getTrans_id());
        csjJiliOrder.setClientName(user.getClientName());
        csjJiliOrder.setCreateTime(LocalDateTime.now());
        csjJiliOrder.setModifyTime(LocalDateTime.now());
        save(csjJiliOrder);
        return userDto;
    }

    @Override
    public GetJiliListResult jiliOrderList(String userId, Integer type) {
        GetJiliListResult result=new GetJiliListResult();
        //type 0:全部订单 1:今天订单
        List<CsjJiliOrder> list=null;
        switch (type) {
            case 0:
                list=lambdaQuery()
                        .eq(CsjJiliOrder::getUserId, userId)
                        .list();
                break;
            case 1:
                LocalDateTime startToday = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
                LocalDateTime endToday = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
                list=lambdaQuery()
                        .eq(CsjJiliOrder::getUserId, userId)
                        .ge(CsjJiliOrder::getCreateTime, startToday)
                        .le(CsjJiliOrder::getCreateTime, endToday)
                        .list();
                break;
            default:
        }
        result.setList(list);
        Goods goods = goodsService.getById(14);
        if (goods != null) {
            Integer limitNum = goods.getLimitNum();
            result.setLimitNum(limitNum);
        }
        return result;
    }
}
